﻿using LbangCMS.Areas.Admin.Models;
using LbangCMS.EFModels;
using LbangCMS.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LbangCMS.Areas.Admin.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        // GET: Admin/Home
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            return View();
        }

        public ActionResult EditCompanyInfo()
        {
            var company = GetCompanyInfo();
            var model = new CompanyInfoModel();
            model.Address = company.Address;
            model.Phone = company.Phone;
            model.Zipcode = company.Zipcode;
            model.CompanyName = company.CompanyName;
            model.Fax = company.Fax;
            return View(model);
        }

        [HttpPost]
        public ActionResult EditCompanyInfo(CompanyInfoModel model)
        {
            if(ModelState.IsValid)
            {
                EditCompantyInfo(model.Address, model.Phone, model.CompanyName, model.Fax, model.Zipcode);
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = true, errorMsg = ModelState.ToHtmlMessage() });
            }
        }


        [ChildActionOnly]
        public ActionResult SinglePageNav()
        {
            var pages = GetAllSinglePage();
            var model = new List<SinglePageNavModel>();
            if(pages!=null&&pages.Any())
            {
                foreach (var item in pages)
                {
                    model.Add(new SinglePageNavModel() { Title=item.Title,Code=item.Code});
                }
                
            }
            return PartialView("_SinglePageNav", model);
        }
        private List<SinglePage> GetAllSinglePage()
        {
            using (var db = new Database())
            {
                return db.SinglePages.OrderBy(o => o.ID).ToList();
            }
        }

        private void EditCompantyInfo(string address,string phone,string companyName,string fax,string zipcode)
        {
            using (var db = new Database())
            {
                var companyInfo = db.CompanyInfo.FirstOrDefault();
                if(companyInfo!=null)
                {
                    companyInfo.Address = address;
                    companyInfo.Phone = phone;
                    companyInfo.CompanyName = companyName;
                    companyInfo.Fax = fax;
                    companyInfo.Zipcode = zipcode;
                    db.SaveChanges();
                }
            }
        }
        private CompanyInfo GetCompanyInfo()
        {
            using (var db = new Database())
            {
                return db.CompanyInfo.FirstOrDefault();
            }
        }
    }
}